package moco.blatt6.sqlitedemo;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteDatabase{
	
	private SQLiteDatabase db;
	private static final String DB_NAME = "SQLiteDemo.sqlite";
	private static int VERSION = 1;
	private final String T_NAME = "t_test";
		private final String TR_ID = "_id";
		private final String TR_NAME = "name";
	
	public MySQLiteDatabase(Context context){
		SQLiteOpenHelper sqlhelper = new SQLiteOpenHelper(context, DB_NAME, null, VERSION) {
			@Override
			public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
				
			}
			@Override
			public void onCreate(SQLiteDatabase db) {
				
			}
		};
		
		db = sqlhelper.getWritableDatabase();
		creatTable();
	}	
	
	public long insertRow(String name){
		ContentValues cv = new ContentValues();
		cv.put("name", name);
		try {
			return db.insertOrThrow(T_NAME, "NULL", cv);
		}catch(SQLException sqlex){}
		db.close();
		return -1;
	}
	
	public Cursor selectAll(){
		return db.query(T_NAME, new String[] {TR_ID,TR_NAME}, null, null,null,null, TR_ID + " DESC");
	}
	
	public Cursor selectRow(long id){
		if(id > 0) {
			String selection = TR_ID+"=?";
			String []selectionArgs = new String[] {Long.valueOf(id).toString()};
			return db.query(T_NAME, new String[] {TR_ID,TR_NAME}, selection, selectionArgs,null,null,null);
		}
		return selectAll();
	}
	
	public boolean deleteRow(long id){
		int bla = db.delete(T_NAME, TR_ID+"=?", new String[]{Long.valueOf(id).toString()});
		if(bla > 0) return true;
		else return false;
	}
	
	private void creatTable(){
		String sql = "CREATE TABLE IF NOT EXISTS " + T_NAME +
				"(" +
				TR_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
				TR_NAME +
				")";
		db.execSQL(sql);
	}

}
